package middleware

import (
	"api/internal/types"
	"context"
	jwt "github.com/golangblogs/gojwt"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
)

type AuthTemplateMiddleware struct {
}

func NewAuthTemplateMiddleware() *AuthTemplateMiddleware {
	return &AuthTemplateMiddleware{}
}

func (m *AuthTemplateMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		token := r.Header.Get("token")
		if token == "" {
			response := types.Response{
				Code: 10001,
				Msg:  "token为空",
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, response)
			return
		}
		j := jwt.NewJWT("2211a_mjh123")

		parseToken, err := j.ParseToken(token)
		if err != nil {
			response := types.Response{
				Code: 10002,
				Msg:  "token错误",
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, response)
			return
		}

		ctx := context.WithValue(r.Context(), "userId", parseToken.ID)

		// Passthrough to next handler if need
		next(w, r.WithContext(ctx))
	}
}
